import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/business/models/business_response.dart';
import 'package:edu/pages/supplement/%20shopping_cart/shopping_cart_page.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class ShoppingCartPageLogic extends ChangeNotifier {
  List<CourseOrder> orders = [];
  double? totalPrice;

  bool loading = false;
  bool error = false;
  bool editing = false;

  // 购物车订单id集合
  Set<int> selectedOrderIds = {};

  int? _lastPage; // 最后一页
  int _page = 1; // 当前页
  int _pageSize = 6; // 每页显示数量
  int _itemOffset = 0; // 购物车商品偏移量
  int _totalItems = 0; // 购物车商品总数
  double _totalPriceBackup = 0; // 购物车总价

  CancelToken? _cancelToken;

  // 是否可以加载更多
  bool get canLoadMore {
    if (_lastPage != null) {
      return _page <= _lastPage!;
    } else {
      return true;
    }
  }

  // 内容是否为空
  bool get isContentEmpty => orders.isEmpty;

  // 是否全选
  bool get isAllSelected => selectedOrderIds.length == _totalItems;

  void init() {
    Future.delayed(Duration.zero, () {
      loadOrders();
    });
    AccountInfo.shared.userBrief?.purchasingCourses.forEach((id) {
      selectedOrderIds.add(id);
    });
    ShoppingCartPage.purchasedCourseIdNotifier.addListener(
      _coursePurchaseListener,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _cancelToken?.cancel();
    ShoppingCartPage.purchasedCourseIdNotifier.removeListener(
      _coursePurchaseListener,
    );
  }

  // 课程购买状态监听
  void _coursePurchaseListener() {
    final id = ShoppingCartPage.purchasedCourseIdNotifier.value.item1;
    final price = ShoppingCartPage.purchasedCourseIdNotifier.value.item2;
    final containsOrder = orders.any((order) => order.id == id);

    if (containsOrder) {
      _itemOffset += 1;
      orders.removeWhere((order) => order.id == id);
    }
    _totalItems -= 1;
    _totalPriceBackup -= price;

    if (selectedOrderIds.contains(id)) {
      selectedOrderIds.remove(id);
      if (totalPrice != null) {
        totalPrice = totalPrice! - price;
      }
    }
    notifyListeners();
  }

  // 切换编辑状态
  void toggleEditing() {
    editing = !editing;
    notifyListeners();
  }

  // 切换选择状态
  void selectAll(bool selected) {
    if (selected) {
      AccountInfo.shared.userBrief?.purchasingCourses.forEach((id) {
        selectedOrderIds.add(id);
      });
      totalPrice = _totalPriceBackup;
    } else {
      selectedOrderIds.clear();
      totalPrice = 0;
    }
    notifyListeners();
  }

  // 课程选择状态改变总价
  void courseItemSelectionChanged(int id, bool selected, double price) {
    if (selected) {
      selectedOrderIds.add(id);
      if (totalPrice != null) {
        totalPrice = totalPrice! + price;
      }
    } else {
      selectedOrderIds.remove(id);
      if (totalPrice != null) {
        totalPrice = totalPrice! - price;
      }
    }
    notifyListeners();
  }

  // 购物车结算
  void purchase() async {
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );

      final response = await DataFetcher.shared.businessApi.purchaseCourse(
        selectedOrderIds.toList(),
      );
      EasyLoading.dismiss();

      if (response.code == 0 && response.totalPrice != null) {
        EasyLoading.showSuccess(AppStrings.coursePurchased);
        AccountInfo.shared.coursePurchased(selectedOrderIds.toList());
        for (final order in orders) {
          if (selectedOrderIds.contains(order.id)) {
            _itemOffset += 1;
          }
        }
        orders.removeWhere((order) => selectedOrderIds.contains(order.id));
        _totalItems -= selectedOrderIds.length;
        _totalPriceBackup -= response.totalPrice!;
        totalPrice = 0.0;
        selectedOrderIds.clear();
        notifyListeners();
      } else {
        EasyLoading.showError(
          response.message ?? AppStrings.coursePurchaseFailed,
        );
      }
    } catch (e) {
      log('Error: $e');
      EasyLoading.dismiss();
    }
  }

  // 删除购物车中的订单
  void delete() async {
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );

      final response = await DataFetcher.shared.businessApi
          .removeCourseFromShoppingCart(selectedOrderIds.toList());
      EasyLoading.dismiss();

      if (response.code == 0 && response.totalPrice != null) {
        EasyLoading.showSuccess(AppStrings.deleteSuccess);
        AccountInfo.shared.removeCourseFromShoppingCarts(
          selectedOrderIds.toList(),
        );
        for (final order in orders) {
          if (selectedOrderIds.contains(order.id)) {
            _itemOffset += 1;
          }
        }
        orders.removeWhere((order) => selectedOrderIds.contains(order.id));
        _totalItems -= selectedOrderIds.length;
        _totalPriceBackup -= response.totalPrice!;
        totalPrice = 0.0;
        selectedOrderIds.clear();
        notifyListeners();
      } else {
        EasyLoading.showError(response.message ?? AppStrings.deleteError);
      }
    } catch (e) {
      log('Error: $e');
      EasyLoading.dismiss();
    }
  }

  // 加载购物车订单
  Future<void> loadOrders() async {
    try {
      if (loading) {
        return;
      }
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      loading = true;
      error = false;
      notifyListeners();

      _cancelToken ??= CancelToken();
      final response = await DataFetcher.shared.businessApi
          .getPurchasingCourses(
            offset: _itemOffset,
            page: _page,
            pageSize: _pageSize,
            cancelToken: _cancelToken,
          );
      loading = false;
      EasyLoading.dismiss();

      if (response.code == 0 && response.orders != null) {
        orders.addAll(response.orders!);
        _lastPage = response.pageMeta?.lastPage;
        _page = (response.pageMeta?.currentPage ?? _page) + 1;
        _pageSize = response.pageMeta?.pageSize ?? 6;
        _totalItems = response.pageMeta?.totalCount ?? 0;
        _totalPriceBackup = response.totalPrice ?? 0;
        if (totalPrice == null || totalPrice == 0) {
          totalPrice = _totalPriceBackup;
        }
      } else if (response.code != 0) {
        error = true;
        EasyLoading.showError(response.message ?? '加载失败');
      }
      notifyListeners();
    } on DioException catch (e) {
      EasyLoading.dismiss();
      if (e.type == DioExceptionType.cancel) {
        return;
      }
      loading = false;
      error = true;
      notifyListeners();
      EasyLoading.showError(e.toString());
    } catch (e) {
      log('Error: $e');
    } finally {
      _cancelToken?.cancel();
      _cancelToken = null;
    }
  }
}
